<?php
/**
 *
  * Cat.php
 * @author Artem Azarov <bel-azar@ya.ru>
 * Date: 4/20/12
 * Time: 10:45 AM
 *
 * This is the model class for table "cat".
 *
 * The followings are the available columns in table 'cat':
 * @property string $cat_id
 * @property string $name
 * @property string $color
 * @property string $birthday
 * @property string $description
 * @property string $sex
 * @property string $avatar
 * @property string $del_avatar
 * @property string $type
 * @property string $gal_id
 * @property string $father_id
 * @property string $mother_id
 *
 * @method Cat male
 * @method Cat female
 * @method Cat cats
 * @method Cat spado
 * @method Cat kittens
 */
class Cat extends CActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Cat the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function init()
    {
        $this->onBeforeSave = array($this, 'cleanParents');
        $this->onAfterSave = array($this, 'addGallery');
        $this->onAfterFind = array($this, 'formatDate');
    }
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'cat';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('name, color, sex, type', 'required'),
            array('name, color, avatar', 'length', 'max' => 255),
            array('sex, type', 'length', 'max' => 6),
            array('birthday, description', 'safe'),
            array('cat_id, name, color, birthday, description, sex, avatar, type', 'safe', 'on' => 'search'),
            array('del_avatar', 'boolean'),
            array('avatar', 'unsafe'),
            array('avatar', 'file',
                'types'=>'jpg, gif, png',
                'maxSize'=>1024 * 1024 * 5, // 5 MB
                'allowEmpty'=>'true',
                'tooLarge'=>'File size is more, then 5 mb.',
            ),
            array('father_id, mother_id', 'required', 'on' => 'kitten'),
            array('father_id, mother_id', 'safe', 'on' => 'insert, update'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'cat_id' => Yii::t('cat','Cat'),
            'name' => Yii::t('cat','Name'),
            'color' => Yii::t('cat','Color'),
            'birthday' => Yii::t('cat','Birthday'),
            'description' => Yii::t('cat','Description'),
            'sex' => Yii::t('cat','Sex'),
            'avatar' => Yii::t('cat','Avatar'),
            'del_avatar' => Yii::t('cat','Delete avatar'),
            'type' => Yii::t('cat','Type'),
            'father_id' => Yii::t('cat','Father'),
            'mother_id' => Yii::t('cat','Mother'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('cat_id', $this->cat_id, true);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('color', $this->color, true);
        $criteria->compare('birthday', $this->birthday, true);
        $criteria->compare('description', $this->description, true);
        $criteria->compare('sex', $this->sex, true);
        $criteria->compare('avatar', $this->avatar, true);
        $criteria->compare('type', $this->type, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * @return array
     */
    public function scopes()
    {
        return array(
            'kittens'=>array(
                "condition"=>"type='kitten'"
            ),
            'cats'=>array(
                "condition"=>"type='cat'"
            ),
            'spado'=>array(
                "condition"=>"type='spado'"
            ),
            'male'=>array(
                "condition"=>"sex='male'"
            ),
            'female'=>array(
                "condition"=>"sex='female'"
            ),
        );
    }

    /**
     * @return array
     */
    public function getTypes()
    {
        return array(
            'cat' => Yii::t('cat','Cat'),
            'kitten' => Yii::t('cat','Kitten'),
            'spado' => Yii::t('cat','Spado'),
        );
    }

    /**
     * @return array
     */
    public function getSexes()
    {
        return array(
            'male' => Yii::t('cat','male'),
            'female' => Yii::t('cat','female'),
        );
    }

    public function getAvatar($id, $alias, $title, $image, $width='150', $class='material_img')
    {
        if(isset($image) && file_exists($_SERVER['DOCUMENT_ROOT'].
            Yii::app()->urlManager->baseUrl.
            '/images/'.'/'.$image))
            return CHtml::image(Yii::app()->getBaseUrl(true).'/images/'.'/'.$image, $title,
                array(
                    'width'=>$width,
                    'class'=>$class,
                ));
        else
            return CHtml::image(Yii::app()->getBaseUrl(true).'/images/pics/noimage.gif','No image',
                array(
                    'width'=>$width,
                    'class'=>$class
                ));
    }

    public function getAvatarImage()
    {
        //TODO add file_exsits check
        return Yii::app()->baseUrl.'/images/avatars/' .$this->cat_id;
    }

    /**
     * Create gallery model and attach it to cat
     *
     * @param  CEvent $event
     */
    public function addGallery($event)
    {

        if (Yii::app()->getModule('imgManager') &&
            ($event->sender->isNewRecord || is_null($event->sender->gal_id))) {
            try {
                $gallery = new Gal;
                $gallery->title = $event->sender->name;
                $gallery->save();
                $event->sender->gal_id = $gallery->id;
                $event->sender->isNewRecord = false;
                $event->sender->setScenario('update');
                $event->sender->save();
            } catch (Exception $e) {
                throw new CHttpException('500', 'Cannot create galerry for this cat');
            }

        }
    }

    /**
     * Remove parent ids, if cat type != kitten
     *
     * @param  CEvent $event
     */
    public function cleanParents($event)
    {
        if ($event->sender->type != 'kitten') {
           $event->sender->father_id = null;
           $event->sender->mother_id = null;
        }
    }

    /**
     * Trim time from date
     *
     * @param  CEvent $event
     */
    public function formatDate($event)
    {
       $event->sender->birthday  = Yii::app()->getDateFormatter()->format('yyyy-MM-dd', $event->sender->birthday);
    }


    public function getFathers()
    {
        $cats = Cat::model()->cats()->male()->findAll();
        $result = array();
        foreach ($cats as $cat) {
            $result[$cat->cat_id] = $cat->name;
        }
        return $result;
    }

    public function getMothers()
    {
        $cats = Cat::model()->cats()->female()->findAll();
        $result = array();
        foreach ($cats as $cat) {
            $result[$cat->cat_id] = $cat->name;
        }
        return $result;
    }


    /**
     *  Get parents of all kittens
     * @static
     * @return array
     */
    public static function getActualParents()
    {
        $parents = Yii::app()->db->createCommand()
            ->select('f.cat_id father_id, f.name father_name, f.avatar father_avatar,'
                .'m.cat_id mother_id, m.name mother_name, m.avatar mother_avatar, c.birthday')
            ->from(Cat::model()->tableName() . " c")
            ->join(Cat::model()->tableName() . " f","f.cat_id = c.father_id")
            ->join(Cat::model()->tableName() . " m","m.cat_id = c.mother_id")
            ->where("c.type = 'kitten'")
            ->group("c.birthday")
            ->queryAll();

        return $parents;
    }

    public static function getGroupedKittens()
    {
        $connection = Yii::app()->db;
        $parents = Cat::getActualParents();

        $criteria = new CDbCriteria();
        $criteria->select = '*';

        $groupChildren = array();
        foreach ($parents as $index => $parent) {
            $criteria->addCondition('father_id= '.$connection->quoteValue($parent['father_id'])
                    . ' AND mother_id = '. $connection->quoteValue($parent['mother_id']),
                'OR');

            $parent['birthday'] = Yii::app()->getDateFormatter()->format('yyyy-MM-dd', $parent['birthday']);
            $groupChildren[crc32($parent['father_id'] . $parent['mother_id'] . $parent['birthday'])] =
                array_merge($parent, array('id'=>$index));
        }

        $children = Cat::model()->findAll($criteria);



        foreach ($children as $child) {
            $key = crc32($child->father_id . $child->mother_id . $child->birthday);
            if (isset($groupChildren[$key])) {
                $groupChildren[$key]['kittens'][] = $child;
            }
        }

        return $groupChildren;
    }

}